﻿//---------------------------------------------------------------------------
// 
// File: HtmlTokenType.cs
//
// Copyright (C) Microsoft Corporation.  All rights reserved.
//
// Description: Definition of token types supported by HtmlLexicalAnalyzer
//
//---------------------------------------------------------------------------

namespace HTMLConverter.XamlConverters
{
    using System.Xml.Linq;
    using HTMLConverter.Xml;

    /// <summary>
    /// HtmlToXamlConverter is a static class that takes an HTML string
    /// and converts it into XAML
    /// </summary>
    internal class TableConverter : IConverter
    {
        public Tag Type
        {
            get { return Tag.Table; }
        }

        public XmlElement Convert(XNode htmlNode)
        {
            XmlElement table = new XmlElement(HtmlConverter.Xaml_Span, HtmlConverter.Xaml_Namespace);
            if (htmlNode is XmlElement)
            {
                XmlElement htmlElement = htmlNode as XmlElement;
                for (XNode htmlChildNode = htmlElement.FirstNode; htmlChildNode != null; htmlChildNode = htmlChildNode.NextNode)
                {
                    XmlElement htmlChildElement = htmlChildNode as XmlElement;
                    if (htmlChildElement != null)
                    {
                        switch (htmlChildElement.LowerName)
                        {
                            case "tr":
                                table.AppendChild(Converters.Collection[Tag.TableRow].Convert(htmlChildNode));
                                break;
                            case "thead":
                            case "tbody":
                            case "tfoot":
                                for (XNode htmlInnerChildNode = htmlChildElement.FirstNode; htmlInnerChildNode != null; htmlInnerChildNode = htmlInnerChildNode.NextNode)
                                {
                                    XmlElement htmlInnerChildElement = htmlInnerChildNode as XmlElement;
                                    if (htmlInnerChildElement != null && htmlInnerChildElement.LowerName == "tr")
                                    {
                                        table.AppendChild(Converters.Collection[Tag.TableRow].Convert(htmlInnerChildNode));
                                    }
                                }
                                break;
                        }

                    }
                }
            }

            if (table.FirstNode != null)
            {
                // add break;
                table.AppendChild(HtmlConverter.CteateLineBreak());
                return table;
            }

            return null;
        }
    }
}
